﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Packaging;
using System.IO;
using SmartSpace.Core;
using SmartSapce.ServiceLocation;

namespace SmartSpace.WebApp._console.core
{
    public partial class theme_upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            string outDir = Server.MapPath("~/_temp/") + Guid.NewGuid().ToString("D");
            Stream stream = new MemoryStream(_ctlFileTheme.FileBytes);
            PackageUtil.DecompressFile(stream, outDir);

            DirectoryInfo di = new DirectoryInfo(outDir);
            string file = di.GetFiles("*.xtml")[0].FullName;
            SmartSpace.Core.Theme theme;
            Dictionary<string, string> configs = PackageUtil.ParseXTML(file, out theme);

            // 移动文件
            foreach (string key in configs.Keys)
            {
                string destFile = Server.MapPath("~\\") + configs[key];
                string sourceFile = Path.Combine(outDir, key);

                FileInfo fi = new FileInfo(destFile);
                if (!fi.Directory.Exists)
                {
                    Directory.CreateDirectory(fi.Directory.FullName);
                }

                if (File.Exists(destFile))
                {
                    File.Delete(destFile);
                }
                File.Move(sourceFile, destFile);
            }

            Directory.Delete(outDir, true);

            ICoreService coreService = ServiceLocator.Get<ICoreService>();
            if (coreService.SaveTheme(theme))
            {
                Response.Redirect(_ctlLinkBack.NavigateUrl);
            }
        }
    }
}